<!--风险四色图 superviseInspectRpt-->
<template>
  <Layout>
    <Form ref="queryForm" :model="dataToQuery" :label-width="120">
      <Row class="query-form">
        <Col span="8">
          <FormItem label="所属单位：" prop="order">
            <cascaderDom class="query-form-el" ref="queryOrgCascader"
                         @setOrgInfo='(data)=>{cascaderQueryDomIdChangeHandle(data,"companyId");}'
                         @setOrgname='(data)=>{cascaderQueryDomNameChangeHandle(data,"companyName");}'
                         :currentOrgId="dataToQuery.companyId"
                         :setCurrentName="{label:dataToQuery.companyName, value:dataToQuery.companyId}"
                         :orgTree="true"></cascaderDom>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="二级集团：">
            <two-level-org org-code class="query-form-el" v-model="dataToQuery.twoLevelOrgId"></two-level-org>
          </FormItem>
        </Col>

        <Col span="8" v-if="!switchFlag">
          <!--          <Button @click="switchQuery(true)" class="ivu-btn-switch" type="text">展开∨</Button>-->
          <Button @click="reset" class="ivu-btn-reset">重置</Button>
          <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
        </Col>
        <Col span="8" v-else>
          <FormItem label="填表时间：" prop="content">
            <DatePicker class="query-form-el" v-model="dataToQuery.createRange" format="yyyy-MM-dd" type="daterange"
                        placement="bottom-end" placeholder="请选择登记时间段" style="width: 100%;"
                        @on-change="(date) => onSelectFieldQueryDateRange(date, 'createDate')"></DatePicker>
          </FormItem>
        </Col>
      </Row>
      <Row v-show="switchFlag" class="query-form">
        <Col span="8">
          <FormItem label="整改状态：" prop="state">
            <Select v-model="dataToQuery.state" style="width: 100%;">
              <Option value="1">未闭环企业</Option>
              <Option value="2">闭环企业</Option>
            </Select>
          </FormItem>
        </Col>
        <Col span="8" offset="8">
          <Button @click="switchQuery(false)" class="ivu-btn-switch" type="text">收起∧</Button>
          <Button @click="reset" class="ivu-btn-reset">重置</Button>
          <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
        </Col>
      </Row>
      <Row class="query-form">
        <Col span="24">
          <Button size="large" class="ivu-btn-add" icon="md-add" @click="addInfo">新增</Button>
<!--          <Button type="primary" class="ivu-btn-add" icon="md-cloud-download" @click="exportFormSubmit">导出</Button>-->
        </Col>
      </Row>
    </Form>
    <Table ref='table' :height="tableHeight" no-data-text="没有查询到相关数据!" @on-selection-change='getSelectRows'
           :loading='pageStatus.loading' @on-sort-change="sortChange"
           border :columns="columns1" :data="dataTable">
    </Table>
    <Row style="margin-right:10px;">
      <Col span="24">
        <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize" @on-change="pageChange"
              @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray" show-total show-sizer
              show-elevator/>
      </Col>
    </Row>
    <Modal :title="mode === 'view'?'安全风险四色图详情':'安全风险四色图'" :transfer=false :mask-closable="false"
           v-model="dialogShow" v-if="dataToView && dialogShow" :width=900
           :styles="{height:(mode === 'view'?'450px':'550px')}"
           class-name='limit-height-dialog'>
      <Row>
        <Col span="24">
          <Form ref="dialogForm" :class="mode === 'view'?'modal-view-detail':'rpt-form'" :show-message="false"
                :model="dataToView" :rules="mode === 'view'?{}:ruleCustom" :label-width="mode === 'view'?170:null"
                :label-position="mode === 'view'?'right':'top'">
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label='所属单位：' prop='companyId'>
                  <div v-if="mode === 'view'">{{ dataToView.companyName }}</div>
                  <cascaderDom v-else class="query-form-el" ref="groupOrg"
                               @setOrgInfo='(data)=>{cascaderDomIdChangeHandle(data,"companyId");}'
                               @setOrgname='(data)=>{cascaderDomNameChangeHandle(data,"companyName");}'
                               :currentOrgId="dataToView.companyId"
                               :setCurrentName="{label:dataToView.companyName, value:dataToView.companyId}"
                               :orgTree="true"></cascaderDom>
                </FormItem>
              </Col>
            </Row>

            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label='备注：' prop='desc'>
                  <div v-if="mode === 'view'">{{ dataToView.desc }}</div>
                  <Input v-else class='' placeholder="请填写备注" type='textarea' show-word-limit :maxlength="1024"
                         v-model='dataToView.desc'></Input>
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span="23" class="query-form" style="margin-left: 15px">
                <Button v-if="mode !== 'view'" class="ivu-btn-add" icon="md-add" @click="addItem">新增四色图</Button>
                <Table highlight-row stripe border style="margin-top:10px;margin-bottom: 10px" :max-height="350"
                       :columns="itemColumn" :data="dataToView.riskMapItemList">
                </Table>
              </Col>
            </Row>

            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label='填表人：' prop='registrant'>
                  <div v-if="mode === 'view'">{{ dataToView.createUserName }}</div>
                  <Input v-else type='text' v-model='dataToView.createUserName' readonly></Input>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label='填表时间：' prop='registTime'>
                  <div v-if="mode === 'view'">{{ renderViewDate(dataToView.createDate) }}</div>
                  <DatePicker v-else type="date" placeholder="请选择日期" class="w" v-model='dataToView.createDate'
                              readonly></DatePicker>
                </FormItem>
              </Col>
            </Row>
          </Form>
        </Col>
      </Row>
      <div slot="footer">
        <Button v-if="mode != 'view'" type="primary" class='ivu-btn-save' @click="submit('dialogForm')">确定</Button>
        <Button v-if="mode != 'view'" type="primary" class='ivu-btn-cancel' @click="handleCancel">取消</Button>
        <Button v-if="mode === 'view'" class='ivu-btn-save' @click="dialogShow=false">关闭</Button>
      </div>
    </Modal>
    <Modal :mask-closable="false" :transfer=false v-model="itemModel" :styles="{height:'500px'}"
           :width=600 title="四色图明细" @on-cancel="itemModel=false,  item={}" class-name='limit-height-dialog'>
      <Row>
        <Col span="24">
          <Form ref="itemForm" :class="'modal-form'" :show-message="false" :model="item"
                :rules="itemRuleCustom" label-position="top">
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label='四色图区域：' prop='mapArea'>
                  <Input class='' show-word-limit :maxlength="1024" placeholder="请填写四色图区域" type='textarea'
                         v-model='item.mapArea'></Input>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label='四色图说明：' prop='itemNote'>
                  <Input class='' show-word-limit :maxlength="1024" placeholder="请填写四色图说明" type='textarea'
                         v-model='item.itemNote'></Input>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label="四色图上传：">
                  <div>
                    <Upload ref="uploadItem"
                            :before-upload="(file) => { beforeUploadItem(file, 'id','RiskMap') }"
                            :show-upload-list="true"
                            :format="['jpg','jpeg','png','gif']"
                            accept="image/jpg, image/jpeg,image/png,image/gif,image/bmp"
                            multiple
                            type="drag"
                            :action="fileUrl">
                      <div style="padding: 10px">
                        <Icon type="ios-cloud-upload" size="45" style="color: #3399ff"></Icon>
                        <p>点击将文件拖拽到这里上传</p>
                        <span style="font-size:8px;color: #797a64">支持扩展名：jpg、jpeg、png、gif...</span>
                      </div>
                    </Upload>
                  </div>
                  <div class="demo-upload-list" v-for="(imgItem,index) in item.idFiles" :key='index'>
                    <img :src="imageUrl + imgItem.id" :ref="imgItem.id">
                    <div class="demo-upload-list-cover">
                      <Icon type="ios-eye-outline" @click.native="handleView(imgItem.id)"></Icon>
                      <Icon type="ios-trash-outline" @click.native="removeItemFile(imgItem.id, 'id','RiskMap')"></Icon>
                    </div>
                  </div>
                </FormItem>
              </Col>
            </Row>

          </Form>
        </Col>

      </Row>
      <div slot="footer">
        <Button type="primary" class='ivu-btn-save' @click="itemSubmit('itemForm')">确定</Button>
        <Button type="primary" class='ivu-btn-cancel' @click="itemModel=false, item={}">取消</Button>
      </div>
    </Modal>
    <Modal title="四色图详情" :transfer=false v-model="modal3" class="modal-view-detail" :width=700
           :styles="{top: '10px'}">
      <Form ref="viewForm" :label-width="100">
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="23">
            <FormItem label='四色图区域：' prop='mapArea'>
              <div>{{ item.mapArea }}</div>

            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="23">
            <FormItem label='四色图说明：' prop='itemNote'>
              <div>{{ item.itemNote }}</div>
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="23">
            <FormItem label="四色图：">
              <div v-for="(item,index) in item.idFiles" class="demo-upload-list">
                <img :src="imageUrl + item.id" @click="handleView(item.id)" :ref="item.id">
              </div>
            </FormItem>
          </Col>
        </Row>
      </Form>
      <div slot="footer">
        <Button class='ivu-btn-save' @click="modal3=false">关闭</Button>
      </div>
    </Modal>
    <Modal title="查看图片" v-model="visible">
      <img :src="imageUrl + imgName" v-if="visible" style="width: 100%">
      <div slot="footer">
        <Button class='ivu-btn-save' @click="visible=false">关闭</Button>
      </div>
    </Modal>
  </Layout>
</template>

<script>
import {Api} from '@/api/index.js'
import selectOrg from '@/components/select-org.vue'
import pageCommonFunction from '@/components/pageCommonFunction.js'
import {sessionStorage} from "@/common/cacheUtils";

var cascaderDom = () => import('@/components/cascader-dom.vue');
export default {
  components: {
    cascaderDom, selectOrg
  },
  data() {
    return {
      ...this.createCommonDataField(),
      loadingItems: false,
      companyId: sessionStorage('userId').getObject('userId').companyId,
      environmentProtectionList: [],
      modal3: false,
      modal5: false,
      sceneList: [],
      loadingExtension: false,
      basicList: [],
      columns1: [
        {
          type: 'expand', width: 30,
          fixed: 'left',
          _disableExpand: true,
          render: (h, params) => {
            return h('Table', {
              props: {
                columns: [
                  {key: 'mapArea', title: '四色图区域', align: 'center', minWidth: 120},
                  {key: 'itemNote', title: '四色图说明', align: 'center', minWidth: 120, tooltip: true},
                ],//表头
                data: params.row.riskMapItemList,//内部表格展示的数据
              },
            })//我这里使用的是表格，大家也可以根据自己的实际情况更换别的组件
          }
        },
        {title: '序号', width: 80, fixed: 'left', align: 'center', render: this.indexColumnsRender},
        {key: 'companyName', title: '所属单位', align: 'center', minWidth: 120},
        {key: 'desc', title: '备注', align: 'center', minWidth: 120, tooltip: true},
        {key: 'createUserName', title: '上报人', align: 'center', minWidth: 120},
        {
          key: 'createDate',
          title: '上报时间',
          align: 'center',
          minWidth: 120,
          sortable: "custom",
          render: this.renderCellDate
        },
        this.getActionColumns(),
      ],
      ruleCustom: {
        companyId: [{required: true, message: '请填写所属单位', trigger: 'change',}],
      },
      modal4: false,
      item: {},
      itemModel: false,
      itemAdd: false,
      extensionShow: {
        userId: [{required: true, message: '请选择审批人', trigger: 'change'}],
        explain: [{required: true, message: '请填写延期申请', trigger: 'change'}],
        completeTime: [{
          validator: (rule, value, callback) => {
            if (value == null || value == '' || value == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
      },
      columns2: [

        {
          title: '序号', width: 70, fixed: 'left', align: 'center', render: (h, params) => {
            return h('span', params.index + 1)
          }
        },
        {key: 'mapArea', title: '四色图区域', align: 'center', minWidth: 120},
        {key: 'itemNote', title: '四色图说明', align: 'center', minWidth: 120, tooltip: true},
        {
          title: '操作',
          key: 'action',
          fixed: 'right',
          width: 200,
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h('A', {
                props: {type: 'primary', size: 'small'},
                style: {fontSize: '13px',},
                on: {
                  click: () => {
                    this.item = {...params.row}
                    this.getFilesItem('id', 'RiskMap');
                    this.modal3 = true
                  }
                }
              }, '详情'),
              h('Divider', {props: {type: 'vertical'}}, ''),
              h('A', {
                props: {type: 'primary', size: 'small'},
                style: {fontSize: '13px',},
                on: {
                  click: () => {
                    this.item = {...params.row}
                    this.getFilesItem('id', 'RiskMap');
                    this.itemModel = true
                    this.itemAdd = false
                  }
                }
              }, '修改'),
              h('Divider', {props: {type: 'vertical'}}, ''),
              h('A', {
                props: {type: 'primary', size: 'small'},
                style: {fontSize: '13px', color: 'red'},
                on: {
                  click: () => {
                    this.$Modal.confirm({
                      title: '提示',
                      content: '<p>是否确定删除？</p>',
                      onOk: () => {
                        this.dataToView.riskMapItemList.splice(params.index, 1)
                      }
                    })
                  }
                }
              }, '删除'),
            ])
          }
        }
      ],
      dataToExtension: {},
      itemRuleCustom: {
        mapArea: [{required: true, message: '请填写检查内容', trigger: 'change'}],
      },
      tableHeight: 10,
      igcMap: {},
      approvers: [],
      imgName: '',
      visible: false,
      // api
      imageUrl: Api.interestedPartiesUserFile + "/file/",
      queryUrl: Api.queryRiskMap,
      deleteUrl: Api.deleteRiskMap,
      updateUrl: Api.updateRiskMap,
      saveUrl: Api.saveRiskMap,
      exportUrl: Api.exportRiskMap,


    }
  },
  computed: {
    itemColumn() {
      const columns = [...this.columns2];
      const columns1 = []
      columns.forEach(item => {
        if (this.mode !== 'view') {
          columns1.push(item)
        } else {
          if (item.key !== 'action') {
            columns1.push(item)
          } else {
            columns1.push({
              title: '操作',
              key: 'action',
              fixed: 'right',
              width: 110,
              align: 'center',
              render: (h, params) => {
                return h('div', [
                  h('A', {
                    props: {type: 'primary', size: 'small'},
                    style: {fontSize: '13px',},
                    on: {
                      click: () => {
                        this.item = {...params.row}
                        this.getFilesItem('id', 'RiskMap');
                        this.modal3 = true
                      }
                    }
                  }, '详情'),
                ])
              }
            })
          }
        }
      })
      return columns1
    },
  },
  async mounted() {
    this.setTableHeight();
    this.query();
  },
  methods: {
    ...pageCommonFunction,
    handleView(name) {
      this.imgName = name;
      this.visible = true;
    },
    getSelectModelData(row) {
      this.dataToExtension.userId = row.userId;
      this.dataToExtension.userName = row.userName;
      this.modal5 = false;
    },
    cancel() {
      this.modal4 = false;
    },
    getUser() {
      this.modal5 = true;
    },
    addItem() {
      this.itemModel = true;
      this.itemAdd = true;
      this.item = {
        id: this.get_uuid(),
      }
    },
    beforeUploadItem(file, filedName, type) {
      let formData = new FormData();
      formData.append("files", file); // 文件对象
      let url = this.fileUrl + '/' + this.item[filedName] + '/files/' + type
      this.$http.post(url, formData).then((res) => {
        if (res.data.result == "success") {
          this.$Message.info("文件上传成功")
          this.getFilesItem(filedName, type);
        }
      })
      return false
    },
    async getFilesItem(filedName, type) {
      if (this.item[filedName]) {
        let url = this.fileUrl + '/' + this.item[filedName] + '/files/' + type.split('/')[0]
        await this.$http.get(url).then((res) => {
          if (res.data.result == "success") {
            this.$set(this.item, filedName + 'Files', res.data.data)
            let index = 0;
            res.data.data.forEach(item => {
              this.uploadListPercent[index] = 0;
              this.uploadListVisible[index] = false;
              this.uploadListVisible[item.id] = false;
              index++;
            })
          }
        });
      }

    },
    removeItemFile(id, filedName, type) {
      let url = this.fileUrl + '/file/' + id;
      this.$http.delete(url).then((res) => {
        this.getFilesItem(filedName, type)
      })
    },
    itemSubmit(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          let _this = this
          _this.dataToView.riskMapItemList.splice()
          if (_this.itemAdd) {
            _this.dataToView.riskMapItemList.push(_this.item)
          } else {
            _this.dataToView.riskMapItemList[_this.item._index] = _this.item
          }
          _this.itemModel = false
        } else {
          this.$Message.error('请填报完整!');
        }
      })
    },
    createEmptyDataToAdd() {
      return {
        riskMapItemList: [],
      }
    },
    dictListToMap(arr, key = 'codingCodeId') {
      let map = {}
      arr.map(item => {
        map[item[key]] = item
      })
      return map
    },
    deleteData(params) {
      this.deleteDateAjax(params);
    },
    query() {
      this.dataToQuery.rptType = this.$route.query.id
      this.queryAjax();
    },
    submit(name) {
      this.submitAjax(name);

    },
    switchQuery(flag) {
      this.switchFlag = flag;
      if (!this.switchFlag) {
        this.tableHeight = this.tableHeight + 88;
      } else {
        this.tableHeight = this.tableHeight - 88;
      }
    },
    async afterDataToViewInit() {
      await this.getFiles('fileId');
    }
  },
  watch: {},

}
</script>

<style lang='css' scoped>
.rpt-form {
}

/deep/ .rpt-form .query-form-el {
  width: 100%;
}

.demo-upload-list {
  display: inline-block;
  width: 60px;
  height: 60px;
  text-align: center;
  line-height: 60px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
  margin-right: 4px;
}

.demo-upload-list img {
  width: 100%;
  height: 100%;
}

.demo-upload-list-cover {
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, .6);
}

.demo-upload-list:hover .demo-upload-list-cover {
  display: block;
}

.demo-upload-list-cover i {
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  margin: 0 2px;
}
</style>
